import { defineStore } from 'pinia'
import type { UserModel } from '@/api'
import { UserAPI } from '@/api'
import { decryptStorage, encryptStorage } from '@/utils/crypto'

// 用户设置接口
interface UserSetting {
  remindType?: string
  plateNumber?: string
  remindCount?: number
  accountCount?: number
  memoCount?: number
  oneKeyMoveUrl?: string
  homeSwipers?: string[]
}

// 用户信息接口
interface UserInfo {
  id: string
  username: string
  realname: string
  avatar: string
  sex?: string
  birthday?: string
  userIdentity?: string
  phone?: string
  email?: string
  setting?: UserSetting
  [key: string]: any
}

// 功能项类型定义
export interface FunctionItem {
  id: string
  name: string
  icon: string
  path: string
  sort: number
  class?: string
  desc?: string | null
  count: number
  collect: boolean
}

// 权限接口
interface Permissions {
  Home: (string | FunctionItem)[]
  Setting: string[]
}

interface UserState {
  token: string
  userInfo: UserInfo | null
  roles: string[]
  permissions: Permissions
}

// 定义 store
export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: '',
    userInfo: null,
    roles: [],
    permissions: {
      Home: [],
      Setting: [],
    },
  }),

  getters: {
    isLoggedIn(): boolean {
      return !!this.token
    },
    hasRole(): (role: string) => boolean {
      return (role: string) => this.roles.includes(role)
    },
    hasPermission(): (permission: string, module?: keyof Permissions) => boolean {
      return (permission: string, module: keyof Permissions = 'Home') => {
        return this.permissions[module]?.includes(permission)
      }
    },
    // 获取用户设置
    userSetting(): UserSetting | undefined {
      return this.userInfo?.setting
    },
    // 获取轮播图
    homeSwipers(): string[] {
      return this.userInfo?.setting?.homeSwipers || []
    },
    // 获取挪车码地址
    oneKeyMoveUrl(): string | undefined {
      return this.userInfo?.setting?.oneKeyMoveUrl
    },
  },

  actions: {
    // 登录
    async login(username: string, password: string, code: string) {
      try {
        const result = await UserAPI.login(username, password, code)
        const { token, userInfo } = result
        this.token = token
        this.userInfo = userInfo as UserInfo
        await this.fetchPermissions()
        return true
      }
      catch (error) {
        console.error('Login failed:', error)
        return false
      }
    },

    // 手机验证码登录
    async phoneLogin(phone: string, _verifyCode: string) {
      try {
        // 模拟API调用 - 实际项目中应该替换为真实的API
        await new Promise(resolve => setTimeout(resolve, 1000))

        // 模拟成功响应
        const mockResult = {
          token: `mock_token_${Date.now()}`,
          userInfo: {
            id: 'mock_user_id',
            username: phone,
            avatar: '',
            realname: `用户${phone.slice(-4)}`,
            phone,
            email: '',
            setting: {
              remindType: '1',
              plateNumber: '',
              remindCount: 0,
              accountCount: 0,
              memoCount: 0,
              oneKeyMoveUrl: '',
              homeSwipers: [],
            },
          } as UserInfo,
        }

        this.token = mockResult.token
        this.userInfo = mockResult.userInfo
        this.roles = ['user']

        // 设置模拟权限
        this.permissions = {
          Home: ['user:view'],
          Setting: ['user:setting'],
        }

        return true
      }
      catch (error) {
        console.error('Phone login failed:', error)
        throw error
      }
    },

    // 登出
    async logout() {
      try {
        if (this.token) {
          await UserAPI.logout()
        }
      }
      catch (error) {
        console.error('Logout failed:', error)
      }
      finally {
        this.token = ''
        this.userInfo = null
        this.roles = []
        // 清空权限
        this.permissions = {
          Home: [],
          Setting: [],
        }
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        if (!this.token)
          return null

        const result = await UserAPI.getUserInfo()
        this.userInfo = result as UserInfo
        return result
      }
      catch (error) {
        console.error('Get user info failed:', error)
        return null
      }
    },

    // 获取用户权限
    async fetchPermissions() {
      try {
        const result = await UserAPI.getPermissions()
        console.log('getPermissions', result)

        this.permissions = result
        return result
      }
      catch (error) {
        console.error('Get permissions failed:', error)
        return null
      }
    },

    // 更新用户设置
    async updateUserSetting(setting: Partial<UserSetting>) {
      try {
        if (!this.userInfo)
          return null

        // 调用后端API更新设置
        const result = await UserAPI.updateInfo({
          ...this.userInfo,
          setting: { ...this.userInfo.setting, ...setting },
        } as Partial<UserModel>)
        // 更新本地状态
        if (this.userInfo.setting) {
          this.userInfo.setting = { ...this.userInfo.setting, ...setting }
        }
        return result
      }
      catch (error) {
        console.error('Update user setting failed:', error)
        return null
      }
    },

    // 更新权限
    updatePermissions(permissions: Permissions) {
      this.permissions = permissions
    },
  },

  persist: {
    key: 'ECHO-STORE',
    storage: {
      getItem: (key: string) => {
        return decryptStorage(key)
      },
      setItem: (key: string, value: any) => {
        encryptStorage(key, value)
      },
    },
    paths: ['token', 'userInfo', 'roles', 'permissions'],
  },
})
